package com.gmrz.uaf.crypto.internal.handlers;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class PasswordCipherHandler extends BaseCipherHandler {
    private static final Logger LOG = LogManager.getLogger(PasswordCipherHandler.class);
    private static final String DEFAULT_TRANSFORMATION = "AES/GCM/NoPadding";
    private static final String DEFAULT_PASSPHRASE = "enoynaotdelaeverebtondluohsesarhpssapsiht";
    private static final byte[] DEFAULT_SALT = {31, -1, 62, 71, 45, 24, 42, 92, 31, -97, 105, 78, -24, 19, 122, 94};
    private static final String DEFAULT_PBE_ALGORITHM = "PBKDF2WithHmacSHA1";
    private static final String DEFAULT_SECRET_KEY_ALGO = "AES";
    private static final int DEFAULT_ITERATIONS = 2000;
    private static final int DEFAULT_KEYLENGTH = 128;

    public PasswordCipherHandler() {
        this.transformation = DEFAULT_TRANSFORMATION;
    }

    protected SecretKey getKey() {
        PBEKeySpec keySpec = new PBEKeySpec(DEFAULT_PASSPHRASE.toCharArray(),
                DEFAULT_SALT, DEFAULT_ITERATIONS, DEFAULT_KEYLENGTH);
        try {
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DEFAULT_PBE_ALGORITHM);
            SecretKey tmpKey = keyFactory.generateSecret(keySpec);
            return new SecretKeySpec(tmpKey.getEncoded(), DEFAULT_SECRET_KEY_ALGO);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("PBKDF2WithHmacSHA1 is not available," + e.getMessage(), e);
        } catch (InvalidKeySpecException e) {
            LOG.error("Genearted key is invalid, " + e.getMessage(), e);
        }
        return null;
    }
}
